//
//  MYNewsVC.m
//  MuYing
//
//  Created by tbb on 2019/7/18.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYNewsVC.h"
#import "YQNavTitleView.h"
#import "YQSearchBaseBar.h"
#import "MYNewsSearchVC.h"
#import "MYNewsCategoryCell.h"
#import "YQMYBaseNavigationController.h"
#import "MYNewsParentingCell.h"
#import "MYNewsDetailsHotTopicVC.h"
#import "YQMYBaseNavigationController.h"
#import "YQLocationVC.h"
#import "YJLocationTool.h"
#import "MYBannerModel.h"
#import "MYHomeDynamicModel.h"
//#import "MYDynamicDetailsVC.h"
#import "MYNewsHotModel.h"
#import "MYNewsSearchCell.h"
#import "MYNewsHotActionSearchVC.h"
#import "MYNewsHotActionDetailsVC.h"
//#import "MYNewsGoodsRecommendModel.h"

@interface MYNewsVC ()<YQSearchBaseBarDelegate>
@property (nonatomic, strong) YQSearchBaseBar * searchBar;
@property (nonatomic, strong) QMUIButton * localeBtn;
@property (nonatomic , strong) YJLocationTool *locationTool;
@property (nonatomic, strong) NSMutableArray * bannerArr;

@property (nonatomic, strong) NSMutableArray * recommendGoodsArr;
@end

@implementation MYNewsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSearchView];
    [self wr_setNavBarBarTintColor:HexColor(0xFAFAFA)];
}
-(void)setupSearchView {
    YQNavTitleView *navView = [YQNavTitleView new];
    navView.frame = CGRectMake(0, 0, kScreenWidth, 44);
    navView.intrinsicContentSize = CGSizeMake(kScreenWidth, 44);
    self.navigationItem.titleView = navView;
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = HexColor(0xFAFAFA);//UIColor.whiteColor;
    [navView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 44));
    }];
    [bgView addSubview:self.searchBar];
    
    [bgView addSubview:self.localeBtn];
    [self.localeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12);
        make.centerY.mas_equalTo(self.searchBar.mas_centerY).mas_equalTo(0);
        make.left.mas_equalTo(self.searchBar.mas_right).mas_equalTo(12);
    }];
}
-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-Height_TabBar);
    kYQREGISTERTABLEVIEWCHeaderFooter([MYNewsBannersHeader class])
    kYQREGISTERTABLEVIEWCELL([MYNewsCategoryCell class])
    kYQREGISTERTABLEVIEWCNIBHeaderFooter(@"MYNewsMoreHeader")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYNewsSearchCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYHomeSearchCell");
    kYQREGISTERTABLEVIEWCELL([MYNewsParentingCell class])
    
    NSString *userCityId = [Config currentConfig].city;
    if ([userCityId isEqualToString:@"<null>"] || userCityId.length == 0 ) {
        if (![self.locationTool startLocation]) {
            //设置默认地区
            [_localeBtn setTitle:@"深圳" forState:(UIControlStateNormal)];
        }else{
            ws(self);
            self.locationTool.loctionBlock = ^(NSString *longitude, NSString *latitude, NSString *cityName, NSError *err) {
                if ([cityName removeStringSpace].length == 0) {
                    return;
                }
                [Config currentConfig].city = cityName;
                [Config currentConfig].longitude = longitude;
                [Config currentConfig].latitude = latitude;
                
                
                
                [weakself.localeBtn setTitle:cityName forState:(UIControlStateNormal)];
            };
        }
    }
    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self bannersData];
        [self recommendGoodsData];
    }];
    [self bannersData];
    [self recommendGoodsData];
}

-(void)bannersData {
    
    [YQPNetWorkingManager sendGetRequest:kBANNERS_URL(@"2") parameters:nil success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [self stopRefresh];
        if (responseObject.code == 0) {
            [self.bannerArr removeAllObjects];
            NSArray *arr = [NSArray modelArrayWithClass:MYBannerModel.class json:responseObject.data];
            for (MYBannerModel *bannerModel in arr) {
                if (bannerModel.url) {
                    [self.bannerArr addObject:bannerModel.url];
                }
            }
            [self.listTableView reloadData];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        [self stopRefresh];
    }];
    
}

- (void) recommendGoodsData {
  
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"informationCategoryId"] = @"7";
    parameters[@"keyword"] = @"";
    parameters[@"limit"] = @"10";
    parameters[@"page"] = @"1";
    
    [YQPNetWorkingManager sendPostRequest:kPOST_INFORMATION_ARTCLE_LIST_URL parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [self stopRefresh];
        if (responseObject.code == 0) {
            [self.recommendGoodsArr removeAllObjects];
            NSArray *arr = [NSArray modelArrayWithClass:MYNewsHotModel.class json:responseObject.data[@"list"]];
            [self.recommendGoodsArr addObjectsFromArray:arr];
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        [self stopRefresh];
        YQUITIPSERROR(error)
    }];
    
}
#pragma makr -- lazy
-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(12, 0, SCREEN_WIDTH - 100, 28)];
        _searchBar.top = 12;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"搜索您要的资讯");
    }
    return _searchBar;
}
-(QMUIButton *)localeBtn {
    if (!_localeBtn) {
        _localeBtn = [QMUIButton buttonWithType:0];
        _localeBtn.titleLabel.font = kSystemMedium(14);
        [_localeBtn setTitleColor:kAPPMainTitleColor forState:(UIControlStateNormal)];
        _localeBtn.imagePosition = QMUIButtonImagePositionRight;
        _localeBtn.spacingBetweenImageAndTitle = 2;
        
        [_localeBtn setImage:YQIMG(@"news_top_locale_d_icon") forState:(UIControlStateNormal)];
        [_localeBtn setImage:YQIMG(@"news_top_locale_s_icon") forState:(UIControlStateSelected)];
        [_localeBtn addTarget:self action:@selector(localeAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_localeBtn setTitle:@"深圳" forState:(UIControlStateNormal)];
    }
    return _localeBtn;
}
- (YJLocationTool *)locationTool
{
    if (!_locationTool) {
        _locationTool = [[YJLocationTool alloc] init];
        _locationTool.blockType = YJLocationBlockTypeLogAndLat;
    }
    return _locationTool;
}
-(NSMutableArray *)bannerArr {
    if (!_bannerArr) {
        _bannerArr = [NSMutableArray array];
    }
    return _bannerArr;
}

-(NSMutableArray *) recommendGoodsArr {
    if (!_recommendGoodsArr) {
        _recommendGoodsArr = [NSMutableArray array];
    }
    return _recommendGoodsArr;
}

#pragma makr -- lazy end
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.localeBtn.selected = NO;
}

-(void)localeAction:(QMUIButton *)sender {
    return;
    sender.selected = !sender.selected;
    YQLocationVC *locationVC = [[YQLocationVC alloc] init];
    YQMYBaseNavigationController *navVC = [[YQMYBaseNavigationController alloc] initWithRootViewController:locationVC];
    ws(self);
    locationVC.selectCityBlack = ^(NSString * _Nonnull cityModel) {
        [weakself.localeBtn setTitle:cityModel forState:(UIControlStateNormal)];
    };
    [self.navigationController presentViewController:navVC animated:YES completion:nil];
}
#pragma makr -- <YQSearchBaseBarDelegate>
- (BOOL)yq_searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    MYNewsSearchVC *searchVC = [[MYNewsSearchVC alloc] init];
    YQMYBaseNavigationController *nav = [[YQMYBaseNavigationController alloc] initWithRootViewController:searchVC];
    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self.navigationController presentViewController:nav animated:true completion:nil];
    //[self.navigationController pushViewController:searchVC animated:true];
    return NO;
}
#pragma makr -- <YQSearchBaseBarDelegate> end

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 1) {
        return self.recommendGoodsArr.count;
    }
    return 1;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        MYNewsCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsCategoryCell"];
        cell.cityName = self.localeBtn.titleLabel.text;
        return cell;
    }else if (indexPath.section == 1) {
        MYNewsHotModel *dynamicModel = nil;
        if (indexPath.row < self.recommendGoodsArr.count) {
            dynamicModel = self.recommendGoodsArr[indexPath.row];
        }
        MYNewsSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsSearchCell"];
        cell.titleLb.text = dynamicModel.title;
        cell.timeLb.text = dynamicModel.createTimeStr;
        [cell.newsIcon setImageURL:YQSTRINGTOURL(dynamicModel.informationImage)];
        cell.likeCountLb.text = [NSString stringWithFormat:@"%@ %@",kYQLS(@"浏览量"),dynamicModel.likeNumber];
        
        return cell;
    }else{
        
    }
    MYNewsParentingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsParentingCell"];
    cell.navVC = self.navigationController;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 212;
    }else if (indexPath.section == 1) {
        return 97;
    }
    return 2*kNEWS_PARENTING_LIST_H + 74 + 44;
//    return 452;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        
        MYNewsHotModel *dynamicModel = nil;
        if (indexPath.row < self.recommendGoodsArr.count) {
            dynamicModel = self.recommendGoodsArr[indexPath.row];
        }
        
        MYNewsHotActionDetailsVC *detailsVC = [MYNewsHotActionDetailsVC new];
        detailsVC.newsModel = dynamicModel;
        kYQPUSH(detailsVC);

    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        MYNewsBannersHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYNewsBannersHeader"];
        header.imageUrlStrArr = self.bannerArr;
        return header;
    }else{
        MYNewsMoreHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYNewsMoreHeader"];
        header.contentView.backgroundColor = UIColor.whiteColor;
        if (section == 1) {
            header.titleLb.text = kYQLS(@"好物推荐");
            [header.moreBtn addTapAction:^(id  _Nonnull sender) {
                MYNewsHotActionSearchVC *hotActionSearch = [[MYNewsHotActionSearchVC alloc] init];
                hotActionSearch.categoryId = @"7";
                [self.navigationController pushViewController:hotActionSearch animated:true];
            }];
        }else{
            header.titleLb.text = kYQLS(@"亲子游");
        }
        return header;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return (kYQPScreenWidth - 24) * 140/351.0 + 24;
    }
    return 51;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
@end
